/*
 * Copyright (c) 2022 The red-star Project
 *
 * Licensed under the Apache License, version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.inyourcode.core.monitor.iml;

import com.inyourcode.core.GlobalConstants;
import com.inyourcode.core.monitor.api.AbstractMonitorOpt;
import com.inyourcode.core.util.StackTraceUtil;
import io.netty.channel.Channel;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author JackLei
 */
public class MonitorOpt4Help extends AbstractMonitorOpt {
    private static final Logger LOGGER = LoggerFactory.getLogger(MonitorOpt4Help.class);

    @Override
    public String opt() {
        return "help";
    }

    @Override
    public String description() {
        return "帮助信息";
    }


    @Override
    public void process(Channel channel, CommandLine commandLine) {
        StringBuffer optionsBuffer = new StringBuffer();
        try {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("monitor", this.options);
            Method method = formatter.getClass().getDeclaredMethod("renderOptions", new Class[]{StringBuffer.class, int.class, Options.class, int.class, int.class});
            method.setAccessible(true);
            method.invoke(formatter, optionsBuffer, 74, this.options, 1, 3);
            formatter.getClass().getDeclaredMethod("renderOptions", new Class[]{StringBuffer.class, int.class, Options.class, int.class, int.class});
        } catch (NoSuchMethodException e) {
            LOGGER.error("options format error, {}", StackTraceUtil.stackTrace(e));
        } catch (IllegalAccessException e) {
            LOGGER.error("options format error, {}", StackTraceUtil.stackTrace(e));
        } catch (InvocationTargetException e) {
            LOGGER.error("options format error, {}", StackTraceUtil.stackTrace(e));
        }

        channel.writeAndFlush("usage: monitor" + GlobalConstants.NEWLINE + optionsBuffer.toString());
    }
}
